package cantools

import (
	fd "gitee.com/CoolguyHolmes/socketcan-fd"
	"io"
	"time"
)

// RepeaterInit , fileName string, canInterfacesName ...string
func RepeaterInit(opts ...repeaterOptions) *Repeater {
	o := newRepeaterOption(opts)
	fd := FdInit(o.fdName)

	if o.fdName == o.can.mirrorPath {
		o.can.mirror = false // 防止循环读写
	}

	return &Repeater{
		fd: fd,
		c:  o.can,
	}
}

func (r *Repeater) Close() {
	r.fd.Close()
	r.c.Close()
}

func (r *Repeater) Replay() {
	replayCh := make(chan *fd.RawFrame, 0)
	go func(ch chan<- *fd.RawFrame) {

		i := 0
		for {
			frameString, readerError := r.fd.Reader.ReadString('\n')

			if readerError == io.EOF {
				// if EOF: close channel
				close(ch)
				return
			}
			i++
			ch <- r.c.serialization.Deserialize(frameString)
		}
	}(replayCh)
	r.send(replayCh)
}

const ms = 1000000

func (r *Repeater) send(replayCh <-chan *fd.RawFrame) {
	frame, ok := <-replayCh
	if !ok {
		return
	}
	frameStart := frame.Time
	timeStart := time.Now().UnixNano()
	for {
		time.Sleep(time.Millisecond) // 在分时操作系统中这个数值太小可能是没有意义的
		for time.Now().UnixNano()-timeStart >= int64(frame.Time-frameStart)*ms {
			r.c.Send(frame)
			frame, ok = <-replayCh
			if !ok {
				return
			}

		}
	}

}

func (r *Repeater) RegisterSerialization(serialization Serialization) {
	r.c.serialization = serialization
	return
}
